using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using System.IO;

namespace SpriteBuilder
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        private IntPtr drawSurface;
        public MainFrameForm EditorForm;

        Camera2D Camera;
        TextureElementsManager ElementManager;
        InputManager input;

        public Game1(IntPtr DrawSurface)
        {
            drawSurface = DrawSurface;
            Content.RootDirectory = "Content";
            graphics = new GraphicsDeviceManager(this);
            graphics.PreparingDeviceSettings += new EventHandler<PreparingDeviceSettingsEventArgs>(graphics_PreparingDeviceSettings);
            System.Windows.Forms.Control.FromHandle((this.Window.Handle)).VisibleChanged += new EventHandler(Game1_VisibleChanged);
            Mouse.WindowHandle = DrawSurface;
        }


        void graphics_PreparingDeviceSettings(object sender, PreparingDeviceSettingsEventArgs e)
        {
            e.GraphicsDeviceInformation.PresentationParameters.DeviceWindowHandle = drawSurface;
        }

        private void Game1_VisibleChanged(object sender, EventArgs e)
        {
            if (System.Windows.Forms.Control.FromHandle((this.Window.Handle)).Visible == true)
            {
                System.Windows.Forms.Control.FromHandle((this.Window.Handle)).Visible = false;
            }
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            Camera = new Camera2D(GraphicsDevice);
            input = new InputManager(Camera);
            ElementManager = new TextureElementsManager(EditorForm);
            LineManager.init(GraphicsDevice);
            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
            MouseState m = Mouse.GetState();
            KeyboardState k = Keyboard.GetState();
            MouseCondition res = input.Update(gameTime, m, k, GraphicsDevice);

            if(res != 0)
                Console.WriteLine(res);

            ElementManager.Update(gameTime, input);

            if (m.ScrollWheelValue != 0)
                throw new Exception("bla");

            if (k.IsKeyDown(Keys.Q))
                Camera.Zoom += 0.1f;
            if (k.IsKeyDown(Keys.E))
                Camera.Zoom -= 0.1f;
            if (k.IsKeyDown(Keys.W))
                Camera.Position += new Vector2(0, -1);
            if (k.IsKeyDown(Keys.S))
                Camera.Position += new Vector2(0, 1);
            if (k.IsKeyDown(Keys.A))
                Camera.Position += new Vector2(-1, 0);
            if (k.IsKeyDown(Keys.D))
                Camera.Position += new Vector2(1, 0);

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here
            spriteBatch.Begin(SpriteSortMode.FrontToBack, null, SamplerState.PointClamp, null, RasterizerState.CullNone,null,Camera.getTransform(GraphicsDevice));
            //if (FrameAuswahl != null)
            //    FrameAuswahl.Draw(spriteBatch);
            //if (fertigeFrameAuswahl != null)
            //    fertigeFrameAuswahl.Draw(spriteBatch);
            ElementManager.Draw(spriteBatch);
            LineManager.Draw(spriteBatch);
            spriteBatch.End();

            base.Draw(gameTime);
        }

        internal void rezise(int width, int height)
        {
            graphics.PreferredBackBufferWidth = width;
            graphics.PreferredBackBufferHeight = height;
            graphics.ApplyChanges();
        }

        public void loadFrame(Stream stream)
        {            
            Texture2D tmpTex = Texture2D.FromStream(GraphicsDevice,stream);
            //FrameAuswahl = new EditorTextureElement(tmpTex, new Vector2(10, 10));
            //fertigeFrameAuswahl = new EditorTextureElement(tmpTex, new Vector2(20, 10));
            ElementManager.insertElement(new EditorTextureElement(tmpTex, new Vector2(0, 0)));
        }
    }
}
